package cn.com.headfree.util;

import cn.com.headfree.mouldshow.controller.ExportWordController;
import com.deepoove.poi.XWPFTemplate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 导出word工具类
 */
public class WordExportUtil {

//    private static Logger log= Logger.getLogger(WordExportUtil.class);
    private static final Logger log = LogManager.getLogger(WordExportUtil.class);

    private WordExportUtil(){}

    /**
     * 在本地生成word文档
     * @param response
     * @param result              结果对象
     * @param pathOfTemplate      须要是绝对路径，末尾是\  如D:\
     * @param templateName        模板名称
     * @param filename            本地生成word名称
     */
    public static void exportWord(HttpServletResponse response, Object result, String pathOfTemplate, String templateName, String filename, ResourceLoader resourceLoader){
        XWPFTemplate template=null;
        FileOutputStream out=null;
        try {
            if (result==null){
                log.error("未查询到相关信息!!!");
                return;
            }
            Resource resource = resourceLoader.getResource("classpath:templates/"+templateName);
            InputStream is = resource.getInputStream();
            template = XWPFTemplate.compile(is).render(result);
//            template = XWPFTemplate.compile(pathOfTemplate+templateName).render(result);
//            template = XWPFTemplate.compile("templates/"+templateName).render(result);//行不通
//            template = XWPFTemplate.compile(WordExportUtil.class.getClassLoader().getResourceAsStream("templates/"+templateName)).render(result);

//            String tempfilePath=pathOfTemplate+ UUID.randomUUID() +"out_简历.docx";
            String tempfilePath= UUID.randomUUID() +"out_简历.docx";
            out = new FileOutputStream(tempfilePath);
            template.write(out);
            out.flush();
            //response导出
            log.info("start response wordfile");
            responseWord(response,tempfilePath,filename);
            log.info("response wordfile success");
        }catch (Exception e){
            log.error("生成本地word异常:",e);
        }finally {
            try {
                if (out!=null){
                    out.close();
                }
            }catch (Exception e){
                log.error("关闭out异常",e);
            }

            try {
                if (template!=null){
                    template.close();
                }
            }catch (Exception e){
                log.error("关闭template异常",e);
            }
        }
    }

    static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");

    private static void responseWord(HttpServletResponse response,String path,String filename){
        File file = null;
        InputStream in = null;
        ServletOutputStream out = null;
        try{
            //简历名称，名称+时间戳+文档后缀名
//            String downloadFileName="个人信息"+simpleDateFormat.format(new Date())+".docx";
            String downloadFileName=filename+simpleDateFormat.format(new Date())+".docx";
            file = new File(path);
            in = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/msword");
            response.setHeader("Cache-Control", "");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(downloadFileName, "UTF-8"))));
            out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int bytesToRead = -1;
            // 用响应对象response中的输出流读取生成好的文件
            while ((bytesToRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        }catch (Exception ex){
            log.error("product word fail..",ex);
        }finally {
            if (in != null) try {
                in.close();
                if (out != null) out.close();
                if (file != null) file.delete(); // 删除临时文件
            } catch (IOException e) {
//                System.out.println("删除删除临时文件出错");
                log.error("删除删除临时文件出错:"+e);
            }
        }
    }


    /**
     * 在本地生成word文档
     * @param response
     * @param result              结果对象
     * @param pathOfTemplate      须要是绝对路径，末尾是\  如D:\
     * @param templateName        模板名称
     * @param filename            本地生成word名称
     */
    public static void exportWordByTplResUme(HttpServletResponse response, Object result, String templateName, String filename, ResourceLoader resourceLoader){
        XWPFTemplate template=null;
        FileOutputStream out=null;
        try {
            if (result==null){
                log.error("未查询到相关信息!!!");
                return;
            }
            Resource resource = resourceLoader.getResource("classpath:templates/"+templateName);
            InputStream is = resource.getInputStream();
            template = XWPFTemplate.compile(is).render(result);
            String tempfilePath= UUID.randomUUID() +"个人简历.docx";
            out = new FileOutputStream(tempfilePath);
            template.write(out);
            out.flush();
            //response导出
            log.info("start response wordfile");
            responseWord(response,tempfilePath,filename);
            log.info("response wordfile success");
        }catch (Exception e){
            log.error("生成本地word异常:",e);
        }finally {
            try {
                if (out!=null){
                    out.close();
                }
            }catch (Exception e){
                log.error("关闭out异常",e);
            }

            try {
                if (template!=null){
                    template.close();
                }
            }catch (Exception e){
                log.error("关闭template异常",e);
            }
        }
    }

}
